<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入公告标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择公告类型"
            clearable
          >
            <el-option
              v-for="item in noticeTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择发布状态"
            clearable
          >
            <el-option
              v-for="item in noticeStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="handleAdd"
            >新增公告</el-button
          >
          <!-- <el-button type="success" :icon="Upload" @click="handleImport"
						>批量导入</el-button
					> -->
          <el-button type="warning" :icon="Download" @click="handleExport"
            >导出公告</el-button
          >
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="noticeList"
        border
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="notice-content" v-html="row.content"></div>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="公告标题"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="公告类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getNoticeTypeTag(row.type)">
              {{ getNoticeTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publisher" label="发布人" width="120" />
        <el-table-column prop="publishTime" label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="发布状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getNoticeStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="readCount"
          label="阅读量"
          width="100"
          align="center"
        />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === 'Draft'"
              type="success"
              link
              :icon="Upload"
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button
              v-if="row.status === 'Published'"
              type="warning"
              link
              :icon="Download"
              @click="handleUnpublish(row)"
            >
              撤回
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '新增公告' : '编辑公告'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialog.form"
        :rules="dialog.rules"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="dialog.form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select
            v-model="dialog.form.type"
            placeholder="请选择公告类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in noticeTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="dialog.form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="附件" prop="attachments">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            multiple
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg、png、pdf等格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="dialog.form.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="置顶公告" prop="isTop">
          <el-switch v-model="dialog.form.isTop" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="批量导入公告"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        :action="importUrl"
        :headers="uploadHeaders"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        :before-upload="beforeImport"
        accept=".xlsx, .xls"
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传 Excel 文件，仅支持 .xlsx 或 .xls 格式
            <el-link
              type="primary"
              :underline="false"
              @click="downloadTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Upload,
  Download,
} from "@element-plus/icons-vue";
import {
  getNotices,
  createNotice,
  updateNotice,
  deleteNotice,
  publishNotice,
  unpublishNotice,
  exportNotices,
} from "@/api/notice";
import { getToken } from "@/utils/auth";

// 公告类型选项
const noticeTypes = [
  { label: "通知公告", value: "Notice" },
  { label: "活动通知", value: "Activity" },
  { label: "维修通知", value: "Maintenance" },
  { label: "其他", value: "Other" },
];

// 公告状态选项
const noticeStatus = [
  { label: "草稿", value: "Draft" },
  { label: "已发布", value: "Published" },
  { label: "已撤回", value: "Revoked" },
  { label: "已过期", value: "Expired" },
];

// 查询参数
const queryParams = ref({
  title: "",
  type: "",
  status: "",
  dateRange: [],
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const noticeList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 上传相关配置
const uploadUrl = import.meta.env.VITE_API_URL + "/api/file/upload";
const importUrl = import.meta.env.VITE_API_URL + "/api/notice/import";
const uploadHeaders = {
  Authorization: "Bearer " + getToken(),
};

// 对话框
const dialog = reactive({
  visible: false,
  type: "add",
  form: {
    title: "",
    type: "",
    content: "",
    attachments: [],
    publishTime: "",
    isTop: false,
  },
  rules: {
    title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
    type: [{ required: true, message: "请选择公告类型", trigger: "change" }],
    content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
    publishTime: [
      { required: true, message: "请选择发布时间", trigger: "change" },
    ],
  },
});

// 导入对话框
const importDialog = reactive({
  visible: false,
});

// 获取公告列表
const getList = async () => {
  try {
    loading.value = true;
    const [startDate, endDate] = queryParams.value.dateRange || [];
    const params = {
      ...queryParams.value,
      startDate,
      endDate,
    };
    delete params.dateRange;

    const res = await getNotices(params);
    noticeList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取公告列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增公告
const handleAdd = () => {
  dialog.type = "add";
  dialog.form = {
    title: "",
    type: "",
    content: "",
    attachments: [],
    publishTime: "",
    isTop: false,
  };
  dialog.visible = true;
};

// 编辑公告
const handleEdit = (row) => {
  dialog.type = "edit";
  dialog.form = { ...row };
  dialog.visible = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialog.type === "add") {
      await createNotice(dialog.form);
      ElMessage.success("创建成功");
    } else {
      await updateNotice(dialog.form.id, dialog.form);
      ElMessage.success("更新成功");
    }
    dialog.visible = false;
    getList();
  } catch (error) {
    console.error("保存失败：", error);
  }
};

// 发布公告
const handlePublish = async (row) => {
  try {
    await publishNotice(row.id);
    ElMessage.success("发布成功");
    getList();
  } catch (error) {
    console.error("发布失败：", error);
  }
};

// 撤回公告
const handleUnpublish = async (row) => {
  try {
    await unpublishNotice(row.id);
    ElMessage.success("撤回成功");
    getList();
  } catch (error) {
    console.error("撤回失败：", error);
  }
};

// 删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该公告吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteNotice(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 批量导入
const handleImport = () => {
  importDialog.visible = true;
};

// 导入成功
const handleImportSuccess = (response) => {
  ElMessage.success("导入成功");
  importDialog.visible = false;
  getList();
};

// 导入失败
const handleImportError = (error) => {
  console.error("导入失败：", error);
  ElMessage.error("导入失败");
};

// 导出公告
const handleExport = async () => {
  try {
    const [startDate, endDate] = queryParams.value.dateRange || [];
    const params = {
      ...queryParams.value,
      startDate,
      endDate,
    };
    delete params.dateRange;

    await exportNotices(params);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
  }
};

// 上传成功
const handleUploadSuccess = (response, file) => {
  dialog.form.attachments.push(response.url);
  ElMessage.success("上传成功");
};

// 上传失败
const handleUploadError = (error) => {
  console.error("上传失败：", error);
  ElMessage.error("上传失败");
};

// 上传前校验
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("上传文件大小不能超过 10MB!");
    return false;
  }
  return true;
};

// 导入前校验
const beforeImport = (file) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  if (!isExcel) {
    ElMessage.error("只能上传 Excel 文件!");
    return false;
  }
  return true;
};

// 下载模板
const downloadTemplate = () => {
  window.location.href = import.meta.env.VITE_API_URL + "/api/notice/template";
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 获取公告类型标签
const getNoticeTypeLabel = (type) => {
  return noticeTypes.find((item) => item.value === type)?.label || type;
};

// 获取公告类型标签样式
const getNoticeTypeTag = (type) => {
  const typeMap = {
    Notice: "",
    Activity: "success",
    Maintenance: "warning",
    Other: "info",
  };
  return typeMap[type] || "info";
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    Draft: "info",
    Published: "success",
    Revoked: "warning",
    Expired: "danger",
  };
  return statusMap[status] || "info";
};

// 获取公告状态标签
const getNoticeStatusLabel = (status) => {
  return noticeStatus.find((item) => item.value === status)?.label || status;
};

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return "-";
  return new Date(datetime).toLocaleString();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      gap: 10px;
    }

    .notice-content {
      padding: 20px;
      line-height: 1.6;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .upload-demo {
    .el-upload__tip {
      line-height: 1.2;
      margin-top: 5px;
    }
  }
}
</style>
